<template>
  <div class="sr-only"></div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'GoogleAuthLogin',
  computed: {
    ...mapState({
      toolify_isLogin: (state) => state.toolify_isLogin,
      locale: (state) => state.locale,
    }),
  },
  watch: {
    toolify_isLogin(val) {
      if (val) {
        window.removeEventListener('load', this.gload())
      } else {
        window.addEventListener('load', this.gload())
      }
    },
  },
  data() {
    return {
      googleLoading: false,
      redirectArr: ['lang-login', 'login'],
    }
  },
  mounted() {
    if (!this.toolify_isLogin) {
      window.addEventListener('load', this.gload())
    }
    if (this.$route.query.from && this.redirectArr.includes(this.$route.name)) {
      this.$cookies.set('toolifyRedirect', this.$route.query.from)
    }
  },
  methods: {
    ...mapMutations(['SET_ISLOGIN', 'SET_LANG', 'SET_USERINFO']),
    gload() {
      if (
        window &&
        window.google &&
        window.google.accounts &&
        window.google.accounts.id &&
        !this.toolify_isLogin
      ) {
        window.google.accounts.id.initialize({
          // 主要就是填写client_id
          client_id:
            '86614736892-cd47sqtnst6f9f3o8fvlsijj6nhk46ms.apps.googleusercontent.com',
          callback: this.toGoogleAuthLogin,
        })

        window.google.accounts.id.prompt()
      }
    },
    async toGoogleAuthLogin(content) {
      this.googleLoading = true
      try {
        let req = {}

        if (content) {
          req = {
            credential: content.credential,
            source: this.$cookies.get('utm') || null,
          }
        } else {
          return false
        }

        const res = await this.$axiosApi.authGoogleLogin(req)
        this.googleLoading = false
        if (res && res.code === 200) {
          if (res.data && res.data.user) {
            this.SET_USERINFO(res.data.user)
          }
          if (res.data && res.data.user && res.data.user.language) {
            this.SET_LANG(res.data.user.language)
          }
          this.SET_ISLOGIN(true)
          //this.$message.success(this.$i18n.t('signInSuccess'))
          /* this.$router.push({
            name: this.locale === 'en' ? 'index' : 'lang-index',
          }) */

          if (this.$route.query.from) {
            this.$router.push({
              name: this.$route.query.from,
              params: { lang: this.locale },
            })
          } else {
            this.$router.push({
              path: this.locale === 'en' ? '/' : `/${this.locale}`,
            })
          }
        } else {
          //this.$message.error(res.message)
        }
      } catch (error) {
        this.googleLoading = false
        console.log(error)
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener('load', this.gload())
  },
}
</script>

